package com.yan.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

import com.yan.entity.Role;
import com.yan.services.SpringRedisService;


@Service
public class SpringRedisServiceImpl implements SpringRedisService {

	@Autowired
	private RedisTemplate redisTemplate;
	
	@Override
	public void test() {
//		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
//		RedisTemplate redisTemplate = applicationContext.getBean(RedisTemplate.class);
		Role role = new Role();
		role.setId(1);
		role.setRoleName("小明");
		//以上的set/get方法看似很简单,但是他可能是来自同一连接池的不同的连接,那么为了使得所有操作都来自
		//同一连接,对于多个命令和使用事务时, 可以降低资源的损耗,那么可以使用SessionCallback或者RedisCallback, 但是鉴于RedisCallback过于底层,所以使用
		//sessionCallback
//		SessionCallback<Role> callBack = new SessionCallback<Role>() {
//
//			public Role execute(RedisOperations ops) throws DataAccessException {
//				// TODO Auto-generated method stub
//				ops.boundValueOps("role_1").set(role);
//				Role role2 = (Role) ops.boundValueOps("role_1").get();
//				return role2;
//			}
//			
//			
//		};
//		Role saveRole = (Role) redisTemplate.execute(callBack);
		
		//使用lambda表达式代替匿名类
		SessionCallback callBack = (ops) -> {
			ops.boundValueOps("role_1").set(role);
			Role role2 = (Role) ops.boundValueOps("role_1").get();
			return role2;
		};
		
		Role saveRole = (Role) redisTemplate.execute(callBack);
		System.out.println(saveRole.getRoleName());
	}

}
